<?php
namespace app\admin\library;

class PowerPlug{
    
    protected string $root = '';
    protected string $title = '';

    protected array $children = [];

    public function __construct($root='',$title=''){
        $this->root = $root;
        $this->title = $title;
    }

    /**
     * 获取权限数据
     * @param string $parent
     * @param array $usablePower 用户有权限的
     * @param array $disabledPower 有权限但是禁用的
     * @return array
     */
     
    public function getData(string $parent,string $usablePower, string $disabledPower ){

        if ($parent != '' ) $power = $parent . '.'. $this->root;
        else $power = $this->root;

        if (!$this->inPowerList($power, $usablePower)) return null;

        $children = [];
        foreach ($this->children as  $value) {

            $_children =  $value->getData($power,$usablePower,$disabledPower);

            if ($_children) $children[] = $_children;
        }

        $re = ['power' => $power, 'title' => $this->title];
        
        if ($this->disabledPower($power, $disabledPower)){
            $re['disabled'] = true;
        }else{
            $re['disabled'] = false;
        }
    
        if (count($children) > 0){
            $re['children'] = $children;
        }

        return $re??[];
    }

    public function add(PowerPlug | string $power,string $title = ''){
        
        if (is_object($power) && $power instanceof PowerPlug){
            $this->children[] = $power;
        }

        if (is_string($power)){
            $this->children[] = new PowerPlug($power,$title);
        }
    }

    public function addList(array $data ){
        foreach ($data as $key => $value) {
            
            if (is_array($value) && isset($value['power']) && isset($value['title'])){
                $this->add($value['power'],$value['title']);
            }

            if (is_string($value)){
                $this->add($key,$value);
            }

            if (is_object($value) && $value instanceof PowerPlug){
                $this->add($value);
            }
        }
    }


    private function inPowerList($power,$powerStr){

        if ($powerStr == 'ALL') return true;
       
        $len  = strlen($power);
        if ($powerStr){
            $list = explode(',', $powerStr);

            foreach ($list as $key => $value) {
                if (substr($value, 0, $len) == $power) {
                    return true;
                }
            }
        } 

        
        return false;
    }


    private function disabledPower($power,$powerStr){

        if ($powerStr == 'ALL') return false;
        if ($powerStr){
            $list = explode(',', $powerStr);
            return in_array($power,$list);
        }

        return false;
    }
        
         
}